from flask import Blueprint, request, jsonify
from models.flow import Flow, FlowComponent, FlowConnection
from models import db

flow_bp = Blueprint('flow_bp', __name__)

@flow_bp.route('/flows', methods=['GET'])
def get_flows():
    """获取流程列表"""
    flows = Flow.query.all()
    return jsonify([{
        'id': flow.id,
        'name': flow.name,
        'description': flow.description,
        'created_at': flow.created_at.isoformat(),
        'updated_at': flow.updated_at.isoformat()
    } for flow in flows])

@flow_bp.route('/flows', methods=['POST'])
def create_flow():
    """创建新流程"""
    data = request.json
    flow = Flow(
        name=data['name'],
        description=data.get('description', '')
    )
    db.session.add(flow)
    db.session.commit()
    return jsonify({'id': flow.id, 'name': flow.name})

@flow_bp.route('/flows/<int:flow_id>', methods=['GET'])
def get_flow(flow_id):
    """获取流程详情"""
    flow = Flow.query.get_or_404(flow_id)
    components = FlowComponent.query.filter_by(flow_id=flow_id).all()
    connections = FlowConnection.query.filter_by(flow_id=flow_id).all()
    
    return jsonify({
        'id': flow.id,
        'name': flow.name,
        'description': flow.description,
        'components': [{
            'id': c.component_id,
            'type': c.type,
            'name': c.name,
            'config': c.config,
            'position': {'x': c.position_x, 'y': c.position_y}
        } for c in components],
        'connections': [{
            'id': c.id,
            'source': c.source_component,
            'target': c.target_component,
            'sourceHandle': c.source_handle,
            'targetHandle': c.target_handle
        } for c in connections]
    })

@flow_bp.route('/flows/<int:flow_id>', methods=['PUT'])
def update_flow(flow_id):
    """更新流程"""
    flow = Flow.query.get_or_404(flow_id)
    data = request.json
    
    # 更新流程基本信息
    flow.name = data['name']
    flow.description = data.get('description', '')
    
    # 删除旧的组件和连接
    FlowComponent.query.filter_by(flow_id=flow_id).delete()
    FlowConnection.query.filter_by(flow_id=flow_id).delete()
    
    # 添加新的组件
    for component in data['components']:
        db.session.add(FlowComponent(
            flow_id=flow_id,
            component_id=component['id'],
            type=component['type'],
            name=component['name'],
            config=component['config'],
            position_x=component['position']['x'],
            position_y=component['position']['y']
        ))
    
    # 添加新的连接
    for connection in data['connections']:
        db.session.add(FlowConnection(
            flow_id=flow_id,
            source_component=connection['source'],
            target_component=connection['target'],
            source_handle=connection['sourceHandle'],
            target_handle=connection['targetHandle']
        ))
    
    db.session.commit()
    return jsonify({'message': 'Flow updated successfully'})

@flow_bp.route('/flows/<int:flow_id>', methods=['DELETE'])
def delete_flow(flow_id):
    """删除流程"""
    flow = Flow.query.get_or_404(flow_id)
    db.session.delete(flow)
    db.session.commit()
    return jsonify({'message': 'Flow deleted successfully'}) 